<template>
  <view class="page">
    <!-- 无网络提示 -->
    <u-no-network></u-no-network>
    <!-- 加载动画组件 -->
    <f-loading></f-loading>
    <!-- 第一步设置手机号和密码 -->
    <view class="step1" v-if="!verification">
      <u-icon name="arrow-left" size="22" color="#888888" @click="toBack" class="close"></u-icon>
      <view class="logo">
        <u--image :src="step1IMG" width="100" height="100" mode="widthFix" :fade="false"
                  :show-loading="false"></u--image>
      </view>
      <!-- #ifdef MP-WEIXIN -->
      <!-- 微信小程序一键登录 -->
      <view class="wxTips">为了提供更好的服务，请允许使用微信授权登录</view>
      <view class="wxLogin">
        <u-button @click="onAuthorization" type="error" shape="circle" icon="weixin-fill">微信授权登录</u-button>
      </view>
      <view class="agreement">
        <u-checkbox-group v-model="agreement" placement="column">
          <u-checkbox :name="1" shape="circle" activeColor="#DE2E2E"></u-checkbox>
        </u-checkbox-group>
        我已阅读并同意
        <text class="url"
              @click="onJump('/pages/article/details?id=1518144075075727362')">《用户服务协议》
        </text>
        及
        <text class="url"
              @click="onJump('/pages/article/details?id=1518144894902775809')">《隐私政策》
        </text>
      </view>
      <!--临时解决小程序登录问题-->
<!--      <view class="login" v-if="">
        <view class="input">
          <u-input v-model="form.mobile" type="number" border="none" placeholder="请输入手机号"
                   maxlength="11" @input="changeInput"/>
        </view>
        <view class="input">
          <u-input v-model="form.password" :password="showPassword" border="none"
                   placeholder="请输入登录密码" @input="changeInput">
            <u-icon slot="suffix" :name="showPassword? 'eye' : 'eye-fill'"
                    @click="changeShowPassword" size="20"></u-icon>
          </u-input>
        </view>
      </view>
      <u-button text="登录" type="error" shape="circle" @click="submit"
      ></u-button>-->
      <!-- #endif -->
      <!-- #ifndef MP-WEIXIN -->
      <!-- 常规登录 -->
      <!-- #ifdef H5 -->
      <view class="login" v-if="smsLogin && !$isWeChat">
        <!-- #endif -->
        <!-- #ifdef APP-PLUS -->
        <view class="login" v-if="smsLogin">
          <!-- #endif -->
          <view class="input">
            <u-input v-model="form.mobile" type="number" border="none" placeholder="请输入手机号" maxlength="11"
                     @input="changeMobile"/>
          </view>
        </view>
        <!-- #ifdef H5 -->
        <view class="login" v-if="!smsLogin && !$isWeChat">
          <!-- #endif -->
          <!-- #ifdef APP-PLUS -->
          <view class="login" v-if="!smsLogin">
            <!-- #endif -->
            <view class="input">
              <u-input v-model="form.mobile" type="number" border="none" placeholder="请输入手机号"
                       maxlength="11" @input="changeInput"/>
            </view>
            <view class="input">
              <u-input v-model="form.password" :password="showPassword" border="none"
                       placeholder="请输入登录密码" @input="changeInput">
                <u-icon slot="suffix" :name="showPassword? 'eye' : 'eye-fill'"
                        @click="changeShowPassword" size="20"></u-icon>
              </u-input>
            </view>
          </view>
          <!-- #ifdef H5 -->
          <!-- 微信公众号一键登录 -->
          <view class="wxTips" v-if="$isWeChat">为了提供更好的服务，请允许使用微信授权登录</view>
          <view class="wxLogin" v-if="$isWeChat">
            <u-button @click="wxLogin" type="error" shape="circle" icon="weixin-fill">微信授权登录</u-button>
          </view>
          <!-- #endif -->
          <view class="agreement">
            <u-checkbox-group v-model="agreement" placement="column">
              <u-checkbox :name="1" shape="circle" activeColor="#DE2E2E"></u-checkbox>
            </u-checkbox-group>
            我已阅读并同意
            <text class="url"
                  @click="onJump('/pages/article/details?id=1518144075075727362')">《用户服务协议》
            </text>
            及
            <text
                class="url" @click="onJump('/pages/article/details?id=1518144894902775809')">《隐私政策》
            </text>
          </view>
          <!-- #ifdef H5 -->
          <u-button text="获取验证码" type="error" shape="circle" :disabled="button" @click="sendCode"
                    v-if="smsLogin && !$isWeChat">
          </u-button>
          <u-button text="登录" type="error" shape="circle" :disabled="button" @click="submit"
                    v-if="!smsLogin && !$isWeChat"></u-button>
          <view class="opiton" v-if="!$isWeChat">
            <text @click="onJump('register')">新用户注册</text>
            <text @click="changeType">{{ smsLogin ? '手机号密码登录' : '短信验证码登录' }}</text>
          </view>
          <!-- #endif -->

          <!-- #ifdef APP-PLUS -->
          <u-button text="获取验证码" type="error" shape="circle" :disabled="button" @click="sendCode"
                    v-if="smsLogin">
          </u-button>
          <u-button text="登录" type="error" shape="circle" :disabled="button" @click="submit" v-if="!smsLogin">
          </u-button>
          <view class="opiton">
            <text @click="onJump('register')">新用户注册</text>
            <text @click="changeType">{{ smsLogin ? '手机号密码登录' : '短信验证码登录' }}</text>
          </view>
          <view class="third">
            <view class="title">其他登录方式</view>
            <view class="icon">
              <button class="login_btn">
                <u-image src="/static/images/icon_wx.png" width="60" height="60" class="item"
                         :fade="false" :show-loading="false"></u-image>
              </button>
            </view>
          </view>
          <!-- #endif -->
          <!-- #endif -->
        </view>
        <!-- 第二步输入验证码 -->
        <view class="step2" v-show="verification">
          <u-icon name="close" color="#888888" size="22" class="close" @click="goStep"></u-icon>
          <view class="logo">
            <u--image src="/static/images/icon_step_2.png" width="100" height="100" mode="widthFix"
                      :fade="false" :show-loading="false"></u--image>
          </view>
          <view class="title">请输入手机短信验证码</view>
          <view class="info">已发送至短信验证码至 {{ mobile }}</view>
          <view class="code">
            <u-code-input v-model="form.code" mode="line" :bold="true" borderColor="#DE2E2E" fontSize="22"
                          :hairline="true" @finish="submit"></u-code-input>
          </view>
          <view class="codeBox">
            <u-code ref="uCode" @change="codeChange" start-text="获取验证码" changeText="X秒后,可重新获取验证码"
                    endText="没收到？重新获取验证码" @start="disabled = true" @end="disabled = false"></u-code>
            <text @tap="getCode" :text="tips" :class="[disabled?'disabled':'normal']">{{ tips }}</text>
          </view>
        </view>

        <!-- 注册协议窗口 -->
        <!-- <u-overlay :show="showAgreement">
      <view class="warp">
        <view class="box">
          <view class="title">注册协议及隐私政策</view>
          <scroll-view :scroll-y="true" :scroll-top="scrollTop" :show-scrollbar="true" class="content">
            <u-parse :content="registProtocolInfo"></u-parse>
            <view class="button">
              <view class="bt">
                <u-button shape="circle" @click="toBack">不同意</u-button>
              </view>
              <view class="bt">
                <u-button type="error" shape="circle" @click="confirmAgreement">同意并继续</u-button>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </u-overlay> -->
      </view>
</template>

<script>
import {
  sendLoginSMS,
  login,
  wxMpLogin
} from '@/config/api';
import {
  registProtocol
} from '@/config/agreement.js';
import {
  getUserInfo,
  h5Login
} from '@/config/h5Utils';
import {
  getPhoneInfo,
  getMpUserInfo
} from '@/config/login';
import fLoading from "@/components/common/loading";

export default {
  components: {
    fLoading
  },
  data() {
    return {
      step1IMG: this.$base.ossUrl1 + 'common/icon_step_1.png',

      verification: false,
      smsLogin: true,
      form: {
        mobile: "",
        password: ""
      },
      showPassword: true,
      agreement: [],
      button: true,
      mobile: "",
      showAgreement: false,
      scrollTop: 0,
      registProtocolInfo: "",
      code: "", //uni.login获取的code
      seconds: 60, // 获取验证码倒计时
      tips: '', // 获取验证码文案
      disabled: true
    }
  },
  onLoad(options) {
    this.protocol();
    // #ifndef MP
    this.prevPage(options);
    if (options.code) {
      this.agreement.push(1);
      this.wxLogin();
    }
    // #endif
  },
  onShow() {
    // #ifdef MP
    this.getLoginByUnion();
    // #endif
  },
  methods: {
    // 页面跳转
    onJump(url) {
      uni.navigateTo({
        url: url
      });
    },
    // 返回
    toBack() {
      uni.navigateBack();
    },
    // 返回上一步
    goStep() {
      // #ifndef APP-PLUS
      uni.showModal({
        content: '点击返回将中断登录，确定返回？',
        confirmColor: "#0E9C98",
        cancelColor: "#999999",
        success: (res) => {
          if (res.confirm) {
            this.verification = false;
            this.form = {
              mobile: "",
              password: "",
            };
            this.agreement = [],
                this.button = true;
            this.$refs.uCode.reset();
          }
        }
      });
      // #endif
      // #ifdef APP-PLUS
      uni.$showModal({
        confirmVal: '确定',
        cancelVal: '取消',
        content: '点击返回将中断登录，确定返回？',
      }).then(res => {
        this.verification = false;
        this.form = {
          mobile: "",
          password: "",
        };
        this.agreement = [],
            this.button = true;
        this.$refs.uCode.reset();
      });
      // #endif
    },
    // 更改登录类型
    changeType: function () {
      this.smsLogin = !this.smsLogin;
      this.form = {
        mobile: "",
        password: "",
      };
      this.button = true;
    },
    // 表单输入内容
    changeMobile(e) {
      if (e.length == 11) {
        this.button = false;
      } else {
        this.button = true;
      }
    },
    changeInput() {
      if (this.form.mobile.length == 11 && this.form.password.length >= 6) {
        this.button = false;
      } else {
        this.button = false;
      }
    },
    // 显示/隐藏密码
    changeShowPassword() {
      this.showPassword = !this.showPassword;
      console.log("showPassword", !this.showPassword)
    },
    // 同意注册协议操作
    confirmAgreement() {
      this.agreement.push(1);
      this.showAgreement = false;
    },
    // 获取注册验证码
    sendCode() {
      const agreement = this.agreement;
      const mobile = this.form.mobile;
      if (!this.$u.test.mobile(mobile)) {
        uni.$u.toast('请正确输入手机号');
        return;
      }
      if (agreement.length == 0) {
        uni.$u.toast('请阅读并勾选页面协议');
        return;
      }
      this.getCode(1);
    },
    codeChange(text) {
      this.tips = text;
    },
    getCode(step) {
      if (this.$refs.uCode.canGetCode) {
        const params = {
          phone: this.form.mobile
        }
        sendLoginSMS(params).then((res) => {
          this.mobile = this.form.mobile.substr(0, 3) + "****" + this.form.mobile.substr(7);
          this.verification = true;
          if (step !== 1) {
            uni.$u.toast('验证码已发送');
          }
          this.$refs.uCode.start();
        });
      } else {
        uni.$u.toast('倒计时结束后再发送');
      }
    },
    // 获取注册协议
    protocol() {
      this.registProtocolInfo = registProtocol;
    },
    // 登录操作
    async submit(e) {
      const agreement = this.agreement;
      const mobile = this.form.mobile;
      const password = this.form.password;
      let params = {
        phone: this.form.mobile,
        loginCode: 2
      }
      if (e) {
        params.code = e;
      } else {
        if (!this.$u.test.mobile(mobile)) {
          uni.$u.toast('请正确输入手机号');
          return;
        }
        /*      if (agreement.length == 0) {
                uni.$u.toast('请阅读并勾选页面协议');
                return;
              }*/
        params.pwd = password;
        params.loginCode = 1;
      }
      // 登录操作
      try {
        let res = await login(params);
        console.log(res);
        //  res = res.access_token;
        // 存储token
        uni.setStorageSync('userToken', res);
        // 获取用户信息
        getUserInfo(() => {
          // 返回之前页面
          const url = uni.getStorageSync('loginGotoUrl');
          if (url == '/pages/index/index' || url == '/pages/goods/category' || url ==
              '/pages/cart/index' || url == '/pages/my/index') {
            uni.switchTab({
              url
            });
          } else {
            uni.redirectTo({
              url
            });
          }
          uni.removeStorageSync('loginGotoUrl');
        });
      } catch (res) {
        if (!res.success && res.code == 102 && res.msg == '用户未注册，请前往注册!' && this.verification) {
          setTimeout(() => {
            this.verification = false;
            this.form = {
              mobile: "",
              password: "",
            };
            this.agreement = [],
                this.button = true;
            this.$refs.uCode.reset();
          }, 1000)
        }
      }
    },
    // 获取进入页面url
    prevPage(options) {
      if (!options.code) {
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];
        if (prevPage != undefined) {
          // #ifdef H5
          let redirectUrl = prevPage.__page__.fullPath;
          // #endif
          // #ifdef APP-PLUS
          let redirectUrl = prevPage.$page.fullPath;
          // #endif
          uni.setStorageSync('loginGotoUrl', redirectUrl);
        } else {

          if (!uni.getStorageSync("loginGotoUrl"))
            uni.setStorageSync('loginGotoUrl', '/pages/index/index');
        }
      }
    },
    // 微信公众号一键登录
    wxLogin() {
      if (this.agreement.length == 0) {
        uni.$u.toast('请阅读并勾选页面协议');
        return;
      }
      ;
      h5Login(() => {
        // 返回之前页面
        const url = uni.getStorageSync('loginGotoUrl');
        if (url == '/pages/index/index' || url == '/pages/goods/category' || url ==
            '/pages/cart/index' || url == '/pages/my/index') {
          uni.switchTab({
            url
          });
        } else {
          uni.redirectTo({
            url
          });
        }
        uni.removeStorageSync('loginGotoUrl');
      })
    },
    // 小程序一键登录
    onAuthorization(e) {
      if (this.agreement.length == 0) {
        uni.$u.toast('请阅读并勾选页面协议');
        return;
      }
      ;
      getMpUserInfo(info => {
        console.log(info, '授权信息')
        let httpData = {
          code: this.code,
          nickName: info.nickName || '', //昵称
          avatarUrl: info.avatarUrl || '', //头像
          gender: info.gender || 0, //性别
        }
        if (this.$store.state.distributionId) {
          httpData.distributionId = this.$store.state.distributionId;
        }
        wxMpLogin(httpData).then((res) => {
          // 存储token
          uni.setStorageSync('userToken', res);
          // 获取用户信息
          getUserInfo(() => {
            uni.navigateBack();
          });
        });
      }, err => {
        // this.closeLogin();
        console.log(err)
      })
    },
    // 小程序内获取用户code
    getLoginByUnion() {
      var that = this
      uni.login({
        success(res) {
          console.log(res, "获取code");
          that.code = res.code;
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background-color: #fff;
  padding: 150rpx 50rpx 50rpx 50rpx;
  position: relative;

  .step1 {
    .close {
      position: absolute;
      /* #ifned APP-PLUS */
      top: 30rpx;
      /* #end */
      /* #ifed APP-PLUS */
      top: 100rpx;
      /* #end */
      left: 50rpx;
    }

    .logo {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 100rpx;
    }

    .login {
      margin-top: 10%;

      .input {
        border-radius: 100rpx;
        background-color: #F2F2F2;
        padding: 25rpx 50rpx;
        margin-top: 40rpx;

        &:first-child {
          margin-top: 0;
        }
      }
    }

    .wxTips {
      text-align: center;
      margin-top: 50rpx;
      font-size: 26rpx;
      color: #999999;
    }

    .wxLogin {
      margin: 50rpx 0;
    }

    .agreement {
      font-size: 24rpx;
      margin: 5% 0;
      color: #999999;
      display: flex;
      align-items: center;
      justify-content: center;

      .url {
        color: $u-error;
      }
    }

    .opiton {
      margin-top: 30rpx;
      text-align: center;

      text {
        margin: 0 40rpx;
        position: relative;

        &:first-child {
          &::after {
            content: '';
            position: absolute;
            right: -45rpx;
            top: 12rpx;
            width: 2rpx;
            height: 20rpx;
            background: #dddddd;
          }
        }
      }
    }

    .third {
      position: absolute;
      bottom: 100rpx;
      left: 0;
      width: 100%;
      margin-top: 20rpx;

      .title {
        text-align: center;
        color: #999999;
      }

      .icon {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 40rpx;

        .item {
          margin: 0 30rpx;
        }
      }
    }
  }

  .step2 {
    .close {
      position: absolute;
      top: 50rpx;
      left: 50rpx;
    }

    .logo {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .title {
      text-align: center;
      font-size: 30rpx;
      margin-top: 20rpx;
    }

    .info {
      text-align: center;
      margin: 20rpx 0 20rpx 0;
      color: #999999;
      font-size: 24rpx;
    }

    .code {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .codeBox {
      margin-top: 40rpx;
      text-align: center;

      .normal {
        color: $u-error;
      }

      .disabled {
        color: #F7C8C8;
      }
    }
  }

  // 注册协议
  .warp {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;

    .box {
      width: 90%;
      height: 80%;
      background-color: #fff;
      border-radius: 10rpx;
      padding: 30rpx;
      font-size: 24rpx;

      .title {
        font-size: 34rpx;
        text-align: center;
      }

      .content {
        margin-top: 20rpx;
        height: 94%;
      }

      .button {
        margin-top: 40rpx;
        display: flex;

        .bt {
          width: 48%;

          &:last-child {
            margin-left: 4%;
          }
        }

        ::v-deep .u-button--info {
          background-color: #CCCCCC;
          color: #FFFFFF;
          border: none;
        }
      }
    }
  }
}
</style>
